<template>
    <page-box class="page">
        <template v-slot:header>
            <ask-breadcrumb>
                <ask-breadcrumb-item name="MenuModuleManage"></ask-breadcrumb-item>
                <ask-breadcrumb-item name="ModuleManageList"></ask-breadcrumb-item>
            </ask-breadcrumb>
            <page-search>
                <page-search-column class="tab-column">
                    <el-tabs class="theme-gray" v-model="typeValue" @tab-click="handleTabClick">
                        <el-tab-pane
                            v-for="item in typeList"
                            :label="item.label"
                            :key="item.value"
                            :name="item.value"
                        >
                            <div slot="label" class="el-tab__label">{{item.label}}</div>
                        </el-tab-pane>
                    </el-tabs>
                    <page-search-column class="fixed-column">
                        <page-search-item>
                            <el-input
                                v-model="searchKey"
                                class="pbb__search-input"
                                prefix-icon="el-icon-search"
                                placeholder="请输入关键词搜索模板"
                                clearable
                            ></el-input>
                        </page-search-item>
                        <page-search-item>
                            <el-button
                                type="primary"
                                class="pbb__search-btn"
                                @click="handleSearch()"
                            >
                                查询
                            </el-button>
                        </page-search-item>
                    </page-search-column>
                    <page-search-item>
                        <el-dropdown trigger="click" @command="handleBatchClick">
                            <el-button
                                type="primary"
                                class="pbb__search-btn">
                                批量操作<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item
                                    v-if="_isTownAdminPageAll"
                                    icon="el-icon-paperclip"
                                    command="relationDepartment"
                                    :disabled="batchList.length === 0 || !canBatch.relationDepartment">
                                    <tree-cascader
                                        title="关联部门"
                                        v-model="departmentValue"
                                        filterable
                                        :checkStrictly="true"
                                        :autoClose="false"
                                        @sure="handleBatchRelationDepartment"
                                        :options="departmentList">
                                        批量关联部门
                                    </tree-cascader>
                                </el-dropdown-item>
                                <el-dropdown-item
                                    v-if="_isOperationPage || _isTownAdminPageCustom"
                                    icon="el-icon-delete-solid"
                                    command="remove"
                                    :disabled="batchList.length === 0 || !canBatch.remove">
                                    批量删除
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </page-search-item>
                    <page-search-item class="right">
                        <el-button
                            class="pbb__search-btn"
                            type="primary"
                            v-if="_isOperationPage || _isTownAdminPageCustom"
                            @click="add({})"
                            icon="el-icon-plus">
                            {{ typeValue === "custom" ? "添加自定义表单":"创建标准表单"}}
                        </el-button>
                    </page-search-item>
                </page-search-column>
            </page-search>
        </template>
        <ask-empty-text
            style="min-height: 400px;"
            v-if="tableData.length === 0">
            创建表单后无数据
        </ask-empty-text>
        <el-table
            v-show="tableData.length !== 0"
            :key="$route.name"
            class="pbb__table"
            header-cell-class-name="pbb__table-thead"
            cell-class-name="pbb__table-thead-cell"
            row-class-name="pbb__table-thead-row"
            :data="tableData"
            @selection-change="onTableSelectionChange"
            style="width: 100%">
            <el-table-column
                type="selection"
                header-align="center"
                align="center"
                width="50"
            ></el-table-column>
            <el-table-column
                label="序号"
                align="center"
                type="index"
                width="50">
            </el-table-column>
            <el-table-column
                v-for="(item,key) in tableColumn"
                :key="key"
                :prop="item.prop"
                :label="item.label"
                :width="item.width||'-'"
                :min-width="item.minWidth||'-'"
                align="center"
                show-overflow-tooltip
                >
                <template slot-scope="scope">
                    <template v-if="item.prop === 'status' && scope.row[item.prop] !== ''">
                        <div>
                            <el-tag
                                :type="scope.row[item.prop].type"
                                size="small">
                                {{scope.row[item.prop].label}}
                            </el-tag>
                        </div>
                        <!-- <template v-if="scope.row[item.prop].name === 'REVIEWFAIL'">
                            {{scope.row.opinion}}
                        </template> -->
                    </template>
                    <template v-else>
                        {{scope.row[item.prop]||'-'}}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                fixed="right"
                header-align="center"
                align="center"
                width="240"
                label="操作"
                class-name="option-column">
                <template slot-scope="scope">
                    <el-button
                        @click="query(scope.row)"
                        type="text"
                        size="small">
                        查看
                    </el-button>
                    <template v-if="_isTownAdminPageAll">
                        <!-- <el-button
                            @click="add(scope.row)"
                            type="text"
                            size="small">
                            以此为模板创建
                        </el-button> -->
                        <tree-cascader
                            title="关联部门"
                            v-model="scope.row.departmentValue"
                            filterable
                            :checkStrictly="true"
                            :autoClose="false"
                            @sure="(vm, value)=> handleRelationDepartment(vm,value,scope.row)"
                            :options="departmentList">
                            <el-button
                                type="text"
                                size="small">
                                关联部门
                            </el-button>
                        </tree-cascader>
                    </template>
                    <template v-if="_isOperationPage || _isTownAdminPageCustom">
                        <!-- <el-button
                            @click="edit(scope.row)"
                            type="text"
                            size="small">
                            编辑
                        </el-button> -->
                        <el-button
                            @click="remove(scope.row)"
                            type="text"
                            size="small">
                            删除
                        </el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>
        <template v-slot:footer>
            <el-pagination
                class="pbb__pagination"
                @size-change="onPageSizeChange"
                @current-change="onCurrentPageChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageCount"
            >
            </el-pagination>
        </template>
    </page-box>
</template>

<script lang="ts">
import { Component, Mixins } from "vue-property-decorator";
import { State } from 'vuex-class';
import TableMixin from "../../table.mixin";
import TreeCascader from "../../../components/tree-cascader/index.vue";

@Component({
    name: "ModuleManageHome",
    components: {
        TreeCascader
    }
})
export default class ModuleManageHome extends Mixins(TableMixin) {
    @State(state => state.authArea) authArea: any;
    // 当前用户所处层级菜单
    get userLevel() {
        return this.$getUserLevel(this.authArea.orgCategoryId);
        // return this.$getUserLevel("6");
    }

    get _isOperation() {
        return ['ADMIN', 'OPERATION_ADMIN', 'OPERATION'].includes(this.userLevel.name);
    }

    get _isOperationPage() {
        return this.$route.name === "OperationModuleManageList";
    }

    get _isTownAdminPage() {
        return this.$route.name === "TownAdminModuleManageList";
    }

    get _isTownAdminPageAll() {
        return this._isTownAdminPage && this.typeValue === "all";
    }

    get _isTownAdminPageCustom() {
        return this._isTownAdminPage && this.typeValue === "custom";
    }

    searchKey = "";
    typeValue = "all";
    get typeList() {
        const res: any[] = [
            {
                label: "标准表单",
                value: "all",
                status: "1"
            }
        ];
        if (!this._isOperationPage) {
            res.push({
                label: "自定义表单",
                value: "custom",
                status: "2"
            });
        }
        return res;
    };

    cityCode = "";
    // 表格数据
    // tableData = [];
    // 批量操作数据集合
    batchList: any[] = [];
    canBatch: any = {
        // 是否可以批量关联部门
        relationDepartment: false,
        // 是否可以批量删除
        remove: false
    };

    // 表格渲染格
    // tableColumn: any[] = [
    //     { label: '模板名称', prop: 'name', width: "300" },
    //     { label: '模板描述', prop: 'desc', width: "300" },
    //     { label: '部门', prop: 'department' },
    //     { label: '创建时间', prop: 'createByTime' },
    //     { label: '创建人', prop: 'createByUser' },
    //     { label: '模板状态', prop: 'status' }
    // ];

    get tableColumn() {
        const res: any[] = [
            { label: '模板名称', prop: 'name', width: "300" },
            { label: '模板描述', prop: 'desc', width: "300" },
            { label: '创建时间', prop: 'createByTime' },
            { label: '创建人', prop: 'createByUser' },
            { label: '模板状态', prop: 'status' }
        ];
        if (this._isTownAdminPage) {
            res.splice(1, 0, { label: '部门', prop: 'department' });
        }
        return res;
    }

    searchKey = "";

    departmentValue: any[] = [];
    departmentList: any[] = [];
    // departmentList: any[] = [
    //     {
    //         value: 1,
    //         label: "一级 1",
    //         children: [
    //             {
    //                 value: 4,
    //                 label: "二级 1-1",
    //                 children: [
    //                     {
    //                         value: 9,
    //                         label: "三级 1-1-1"
    //                     },
    //                     {
    //                         value: 10,
    //                         label: "三级 1-1-2"
    //                     }
    //                 ]
    //             }
    //         ]
    //     },
    //     {
    //         value: 2,
    //         label: "一级 2",
    //         children: [
    //             {
    //                 value: 5,
    //                 label: "二级 2-1"
    //             },
    //             {
    //                 value: 6,
    //                 label: "二级 2-2"
    //             }
    //         ]
    //     },
    //     {
    //         value: 3,
    //         label: "一级 3",
    //         children: [
    //             {
    //                 value: 7,
    //                 label: "二级 3-1"
    //             },
    //             {
    //                 value: 8,
    //                 label: "二级 3-2"
    //             }
    //         ]
    //     }
    // ];
    activated() {
        this.initSearchData();
        this.initData(this.currentPage);
    }

    handleTagChange() {
        this.initData();
    }

    handleTabClick() {
        this.initSearchData();
        this.initData();
        // this.batchList = [];
        // this.canReleaseByBatch = false;
        // this.canOfflineByBatch = false;
    }

    checkBtnAuth(item: any, ...status: any[]) {
        const { status: reviewStatus }: any = item;
        return status.includes(reviewStatus.name);
    }

    handleBatchClick(command: any) {
        if (command === "remove") {
            this.remove({}, "batch");
        }
    }

    handleRelationDepartment(vm: any, value: any, row: any) {
        this.updateRelationDepartment(vm, value, [row.id], "single");
    }

    async handleBatchRelationDepartment(vm: any) {
        await this.updateRelationDepartment(vm, this.departmentValue, this.batchList.map((cur: any) => cur.id), "batch");
        this.departmentValue = [];
    }

    async updateRelationDepartment(vm: any, value: any, ids: any[], type: string) {
        console.log(value, ids, type);
        vm.loader(true);
        const response = await this.$server["moduleManage/norm-list/updateDept"]({
            data: {
                deptIds: value,
                dimensionalityId: ids
            }
        });
        if (this.responseHasError(response)) {
            vm.loader(false);
            return;
        }
        this.$message({
            message: '部门已修改',
            type: 'success',
            duration: 1500
        });
        vm.loader(false);
        vm.close();
        this.initData(this.currentPage);
    }

    // 表格选中修改
    onTableSelectionChange(selectList: any[]) {
        console.log(selectList);
        const relationDepartmentList = selectList;
        this.canBatch.relationDepartment = relationDepartmentList.length === selectList.length;
        const removeList = selectList;
        this.canBatch.remove = removeList.length === selectList.length;
        this.batchList = selectList;
    }

    getConfirmInfo(item: any, type: string, handleModel = "single") {
        const confirmInfo: any = {
            msg: '',
            content: '',
            ids: []
        };
        if (type === 'remove') {
            confirmInfo.content = "是否确认删除模板?";
            confirmInfo.msg = "删除成功！";
        }
        if (type === 'release') {
            confirmInfo.content = "是否确认发布模板?";
            confirmInfo.msg = "已发布！";
        }
        let ids = [];
        if (handleModel === "batch") {
            confirmInfo.content = "共计" + this.batchList.length + "条数据，" + confirmInfo.content;
            ids = this.batchList.map(cur => cur.id);
        } else {
            ids = [item.id];
        }
        confirmInfo.ids = ids;
        return confirmInfo;
    }

    onPageSizeChange(pageSize: number) {
        this.pageSize = pageSize;
        this.initData();
    }

    onCurrentPageChange(page: number) {
        this.initData(page);
    }

    async initSearchData() {
        // const tagResponse = await this.$server["moduleManage/tag"]();
        // if (tagResponse.data.code !== 200) {
        //     throw tagResponse.data;
        // }
        // this.tagList = (tagResponse.data.data || []).map((item: any) => {
        //     return {
        //         value: item.id,
        //         label: item.name || ""
        //     };
        // });
        const departmentResponse = await this.$server["moduleManage/department"]({
            data: {
                governmentId: this.authArea.governmentId
            }
        });
        if (this.responseHasError(departmentResponse)) {
            return;
        }
        this.departmentList = this.buildTypeList(departmentResponse.data.data || []);
    }

    getInitParams() {
        return {
            url: "moduleManage/norm-list/list",
            data: {
                templateKind: this.$key2Name({
                    type: this.typeValue,
                    list: this.typeList,
                    name: "status"
                }),
                status: !this._isOperationPage && this.typeValue === "all" ? "1" : "",
                name: this.searchKey || undefined
            }
        };
    }

    buildTableData(list: any) {
        let res: any = [];
        if (list.length === 0) {
            return res;
        }
        res = list.map((cur: any) => {
            return {
                id: cur.id || "",
                name: cur.templateName || "",
                desc: cur.description || "",
                department: cur.departmentNamed || "",
                departmentValue: this.formatTextToArray(cur.departmentIds || ""),
                createByTime: cur.createTime || "",
                createByUser: cur.createUser || "",
                status: this.$getTaskModuleStatus(cur.status || 0),
                source: cur
            };
        });
        return res;
    }

    handleSearch() {
        this.initData();
    }

    add(item: any) {
        this.$router.push({
            name: (this._isOperationPage ? "Operation" : "TownAdmin") + "ModuleManageForm",
            query: {
                moduleId: item.id || ""
            }
        });
    }

    remove(item: any, handleModel?: string) {
        this.triggerConfirm({
            item: item,
            type: "remove",
            handleModel: handleModel || "single",
            sure: async(confirmInfo: any) => {
                // const ids = item.id ? [item.id] : [];
                const response = await this.$server["moduleManage/norm-list/delete"]({
                    params: {
                        id: confirmInfo.ids[0]
                    }
                });
                if (this.responseHasError(response)) {
                    return;
                }
                if (response.data.code !== 200) {
                    throw response.data;
                }
                this.$message({
                    message: confirmInfo.msg,
                    type: 'success',
                    duration: 1500
                });
                this.initData(this.currentPage);
            }
        });
    }

    query(item: any) {
        this.$router.push({
            name: (this._isOperationPage ? "Operation" : "TownAdmin") + "ModuleManageQuery",
            params: {
                type: this.typeValue
            },
            query: {
                id: item.id
            }
        });
    }

    edit(item: any) {
        this.$router.push({
            name: (this._isOperationPage ? "Operation" : "TownAdmin") + "ModuleManageForm",
            query: {
                id: item.id
            }
        });
    }

    release(item: any) {
        this.triggerConfirm({
            item: item,
            type: "release",
            handleModel: "single",
            sure: async(confirmInfo: any) => {
                // const ids = item.id ? [item.id] : [];
                const response = await this.$server["moduleManage/delete"]({
                    params: {
                        id: confirmInfo.ids || []
                    }
                });
                if (this.responseHasError(response)) {
                    return;
                }
                this.$message({
                    message: confirmInfo.msg,
                    type: 'success',
                    duration: 1500
                });
                this.initData(this.currentPage);
            }
        });
    }
}
</script>
